/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nageoffer.shortlink.admin.config;

import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 布隆过滤器配置
 */
@Configuration(value = "rBloomFilterConfigurationByAdmin")
public class RBloomFilterConfiguration {

    /**
     * 创建并初始化用于用户注册的布隆过滤器，以减少数据库查询的缓存穿透问题
     *
     * @param redissonClient Redis客户端，用于存储和操作布隆过滤器
     * @return 初始化后的布隆过滤器对象
     */
    @Bean
    public RBloomFilter<String> userRegisterCachePenetrationBloomFilter(RedissonClient redissonClient) {
        // 获取名为"userRegisterCachePenetrationBloomFilter"的布隆过滤器实例
        RBloomFilter<String> cachePenetrationBloomFilter = redissonClient.getBloomFilter("userRegisterCachePenetrationBloomFilter");
        // 尝试初始化布隆过滤器，参数分别为预期插入的元素数量和假阳性概率
        cachePenetrationBloomFilter.tryInit(100000000L, 0.001);
        // 返回初始化后的布隆过滤器实例
        return cachePenetrationBloomFilter;
    }

    /**
     * 防止分组标识注册查询数据库的布隆过滤器
     *
     * 此方法用于初始化并返回一个布隆过滤器，该过滤器用于缓存渗透控制，
     * 具体目的是减少对数据库的不必要的查询操作，提高系统性能
     *
     * @param redissonClient Redis客户端，用于存储和操作布隆过滤器
     * @return RBloomFilter<String> 返回一个初始化后的布隆过滤器实例，
     *         用于判断某个分组标识是否可能已注册
     */
    @Bean
    public RBloomFilter<String> gidRegisterCachePenetrationBloomFilter(RedissonClient redissonClient) {
        // 获取名为"gidRegisterCachePenetrationBloomFilter"的布隆过滤器实例
        RBloomFilter<String> cachePenetrationBloomFilter = redissonClient.getBloomFilter("gidRegisterCachePenetrationBloomFilter");
        // 尝试初始化布隆过滤器，参数分别为预期插入的元素数量和假阳性概率
        cachePenetrationBloomFilter.tryInit(200000000L, 0.001);
        // 返回初始化后的布隆过滤器实例
        return cachePenetrationBloomFilter;
    }
}